<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<script type="text/javascript">
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    function addRow() {
        var expCode = $('#expCode').val();
        var purchasePrice = $('#purchasePrice').val();
        var batchNo = $('#batchNo').val();
        var quantity = $('#quantity').val();
        if (expCode == null || expCode == '' || typeof(expCode) == 'undefined') {
            toastr.error('没有要添加的数据!');
            return;
        }
        if ($('#purchasePrice').val() == null || $('#purchasePrice').val() == "" || typeof($('#purchasePrice').val()) == "undefined") {
            toastr.error("进货价不能为空!");
            return;
        }
        if ($('#batchNo').val() == null || $('#batchNo').val() == "" || typeof($('#batchNo').val()) == "undefined") {
            toastr.error("批号不能为空!");
            return;
        }
        if ($('#quantity').val() == null || $('#quantity').val() == "" || typeof($('#quantity').val()) == "undefined") {
            toastr.error("入库数量不能为空!");
            return;
        }
        var tbIdx = 0;
            if (typeof($("#contentTable tbody tr:last").attr('xia')) == 'undefined') {
            tbIdx = 0;
        } else {
            tbIdx = Number($("#contentTable tbody tr:last").attr('xia')) + 1;
        }

        //对消入出库金额合计
        var totalMoney = 0.00;
        var oldValue = $('#totalMoney').val();
        totalMoney = new Number(oldValue) + new Number($('#quantity').val()) * new Number($('#purchasePrice').val());
        $('#totalMoney').val(totalMoney);

        var list = $("table tr").find("td:eq(0)");
        var jsonuserinfo = $("#inputForm").serializeObject();
        var datastr = JSON.stringify(jsonuserinfo);
        var trHTML = "<tr xia='" + tbIdx + "'>";
        trHTML += "<td hidden>" + datastr + "</td>";
        trHTML += "<td hidden><input id='infoId" + tbIdx + "' name='expStockList[" + tbIdx + "].infoId' value='" + $('#infoId').val() + "'/></td>";
        trHTML += "<td hidden><input id='expCode" + tbIdx + "' name='expStockList[" + tbIdx + "].expCode' value='" + $('#expCode').val() + "'/></td>";
        trHTML += "<td>" + $('#remarks').val() + "</td>";
        trHTML += "<td hidden>"+ $('#packageNum').val() +"<input type='hidden' id='packageNum" + tbIdx + "' name='expStockList[" + tbIdx + "].packageNum' value='" + $('#packageNum').val() +
        "'/></td>";
        trHTML += "<td>"+ $('#packageSpec').val() +"<input type='hidden' id='packageSpec" + tbIdx + "' name='expStockList[" + tbIdx + "].packageSpec' value='" + $('#packageSpec').val() + "'/></td>";
        trHTML += "<td hidden>"+ $('#packageUnits').val() +"<input type='hidden' id='packageUnits" + tbIdx + "' name='expStockList[" + tbIdx + "].packageUnits' value='" + $('#packageUnits').val() +
        "'/></td>";
        trHTML += "<td>"+ $("#packageUnits option:selected").text() +"</td>";
        trHTML += "<td hidden>" + $('#minSpec').val() + "<input type='hidden' id='minSpec" + tbIdx + "' name='expStockList[" + tbIdx + "].minSpec' value='" + $('#minSpec').val() + "'/></td>";
        trHTML += "<td hidden>" + $('#minUnits').val() + "<input type='hidden' id='minUnits" + tbIdx + "' name='expStockList[" + tbIdx + "].minUnits' value='" + $('#minUnits').val() + "'/></td>";
        trHTML += "<td hidden>" + $("#minUnits option:selected").text() + "</td>";
        trHTML += "<td hidden>" + $('#supplierId').val() + "<input type='hidden' id='supplierId" + tbIdx + "' name='expStockList[" + tbIdx + "].supplierId' value='" + $('#supplierId').val() +
        "'/></td>";
        trHTML += "<td>" + $('#supplierName').val() + "</td>";
        trHTML += "<td><input type='text' id='purchasePrice" + tbIdx + "' class='form-control' name='expStockList[" + tbIdx + "].purchasePrice'  onchange=\"changeFun('purchasePrice'," + tbIdx + ")\" value='" +
        $('#purchasePrice').val() + "'/></td>";
        trHTML += "<td><input type='text' class='form-control' id='batchNo" + tbIdx + "' name='expStockList[" + tbIdx + "].batchNo' value='" + $('#batchNo').val() + "'/></td>";
        trHTML += "<td>" + $('#expireDate').val() + "<input type='hidden' id='expireDate" + tbIdx + "' name='expStockList[" + tbIdx + "].expireDate' value='" + $('#expireDate').val() + "'/></td>";
        trHTML += "<td hidden>"+ $('#sterilizationMethod').val() +"<input type='hidden' id='sterilizationMethod" + tbIdx + "' name='expStockList[" + tbIdx + "].sterilizationMethod' value='" +
        $('#sterilizationMethod').val() +
        "'/></td>";
        trHTML += "<td>"+ $("#sterilizationMethod option:selected").text() +"</td>";
        trHTML += "<td>"+ $('#sterilizationBatchNo').val() +"<input type='hidden' id='sterilizationBatchNo" + tbIdx + "' name='expStockList[" + tbIdx + "].sterilizationBatchNo' value='" + $('#sterilizationBatchNo').val() + "'/></td>";
        trHTML += "<td>"+ $('#sterilizationDate').val() +"<input type='hidden' id='sterilizationDate" + tbIdx + "' name='expStockList[" + tbIdx + "].sterilizationDate' value='" + $('#sterilizationDate').val() + "'/></td>";
        trHTML += "<td><input type='text' id='quantity" + tbIdx + "' class='form-control' name='expStockList[" + tbIdx + "].quantity'  onchange=\"changeFun('quantity'," + tbIdx + ")\" value='" +
        $('#quantity').val() + "'/></td>";
        trHTML += "<td><a href='#' onclick='removeList(this)' class='applyBt btn btn-danger btn-xs'>删除</a></td>"
        trHTML += "</tr>";
        $("#inputForm input").val("");
        $("#contentTable").append(trHTML);
        return loadDiv('rigthCenterDiv', '${ctx}/csm/expStock/expImpExpBalanceForm');
    }

    //表单自动回填的方法
    var fillForm = function($form, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        for ( var key in jsonObj) { // 遍历json字符串
            var objtype = jsonObjType(jsonObj[key]); // 获取值类型
            if (objtype === "array") { // 如果是数组，一般都是数据库中多对多关系
                var obj1 = jsonObj[key];
                for ( var arraykey in obj1) {
                    // alert(arraykey + jsonObj[arraykey]);
                    var arrayobj = obj1[arraykey];
                    for ( var smallkey in arrayobj) {
                        setCkb(key, arrayobj[smallkey]);
                        break;
                    }
                }
            } else if (objtype === "object") { // 如果是对象，啥都不错，大多数情况下，会有 xxxId
                // 这样的字段作为外键表的id

            } else if (objtype === "string") { // 如果是字符串
                var str = jsonObj[key];
                var date = new Date(str);
                if (date.getDay()) { // 这种判断日期是本人懒，不想写代码了，大家慎用。
                    $("[name=" + key + "]", $form).val(str);
                    continue;
                }

                var tagobjs = $("[name=" + key + "]", $form);
                if ($(tagobjs[0]).attr("type") == "radio") {// 如果是radio控件
                    $.each(tagobjs, function(keyobj, value) {
                        if ($(value).attr("val") == jsonObj[key]) {
                            value.checked = true;
                        }
                    });
                    continue;
                }
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            } else { // 其他的直接赋值
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            }

        }
    }

    var setCkb = function(name, value) {
        // alert(name + " " + value);
        // $("[name=" + name + "][value=" + value + "]").attr("checked", "checked");
        // 不知为何找不到具体标签;
        $("[name=" + name + "][val=" + value + "]").attr("checked", "checked");
    }

    var fillckb = function(name, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        var str = jsonObj[name];
        if (typeof str === "string") {
            var array = str.split(",");
            $.each(array, function(key, value) {
                setCkb(name, value);
            });
        }
    }

    var jsonObjType = function(obj) {
        if (typeof obj === "object") {
            var teststr = JSON.stringify(obj);
            if (teststr[0] == '{' && teststr[teststr.length - 1] == '}')
                return "class";
            if (teststr[0] == '[' && teststr[teststr.length - 1] == ']')
                return "array";
        }
        return typeof obj;
    }
    //表单回填EN


</script>
<div class="content-wrap">
    <div class="wrapper" style="bottom: 50px;">
        <ul class="nav nav-tabs">
            <li>
                <a href="#"  onclick="loadDiv('rigthCenterDiv','${ctx}/csm/expStock/form')">对消入出库</a>
            </li>
        </ul>
        <section class="panel panel-default">
            <div class="panel-body">
                <div class="col-lg-12">
<form:form id="inputForm" data-parsley-validate=""  modelAttribute="expStock" onsubmit="return formSaveLoad('mainCenterDiv','inputForm','${ctx}/csm/expStock/save','${ctx}/csm/expStock/index');" method="post" class="form-horizontal">
                    <form:hidden path="infoId"/>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">编码：</label>
                        <div class="col-sm-8">
                            <form:input path="expCode" htmlEscape="false" class="form-control"  maxlength="32" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">名称：</label>
                        <div class="col-sm-8">
                            <form:input path="remarks" id="remarks" htmlEscape="false" class="form-control"  maxlength="64" />
                        </div>
                    </div>
                    <div class="form-group" hidden="hidden">
                        <label class="col-sm-4 control-label">包装数量：</label>
                        <div class="col-sm-8">
                            <form:input path="packageNum" id="packageNum" htmlEscape="false" class="form-control"  maxlength="8" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">规格：</label>
                        <div class="col-sm-8">
                            <form:input path="packageSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">单位：</label>
                        <div class="col-sm-8">
                            <form:hidden path="packageUnits" id="packageUnitsValue"></form:hidden>
                            <form:select path="" id="packageUnits" class="form-control" data-parsley-required="true" disabled="true">
                                <form:option value="" label="" />
                                <form:options items="${fns:getDictList('SPEC_UNIT')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                            </form:select>
                        </div>
                    </div>
                    <div class="form-group" hidden="hidden">
                        <label class="col-sm-4 control-label">最小规格：</label>
                        <div class="col-sm-8">
                            <form:input path="minSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group" hidden="hidden">
                        <label class="col-sm-4 control-label">最小单位：</label>
                        <div class="col-sm-8">
                            <form:hidden path="minUnits" id="minUnitsValue"></form:hidden>
                            <form:select path="" id="minUnits" class="form-control" data-parsley-required="true" disabled="true">
                                <form:option value="" label="" />
                                <form:options items="${fns:getDictList('SPEC_UNIT')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                            </form:select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">厂家：</label>
                        <div class="col-sm-8">
                            <form:hidden path="expSupplierCata.id" id="supplierId"></form:hidden>
                            <form:input path="expSupplierCata.supplierName" id="supplierName" htmlEscape="false" class="form-control"  maxlength="64" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">进价：</label>
                        <div class="col-sm-8">
                            <form:input path="purchasePrice" id="purchasePrice" htmlEscape="false" class="form-control" data-parsley-required="true"/>
                        </div>
                    </div>
                    <div class="form-group" hidden="hidden">
                        <label class="col-sm-4 control-label">折扣：</label>
                        <div class="col-sm-8">
                            <form:input path="discount" htmlEscape="false" class="form-control" value="1" data-parsley-required="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">批号：</label>
                        <div class="col-sm-8">
                            <form:input path="batchNo" id="batchNo" htmlEscape="false" class="form-control"  maxlength="64" data-parsley-required="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">有效期：</label>
                        <div class="col-sm-8">
                            <input id="expireDate" name="expireDate" htmlEscape="false" class="form-control Wdate" data-parsley-required="true" readonly onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" value='<fmt:formatDate value="${expPrice.startDate}" pattern="yyyy-MM-dd HH:mm:ss"/>'/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">灭菌方式：</label>
                        <div class="col-sm-8">
                            <form:select path="sterilizationMethod" id="sterilizationMethod" htmlEscape="false" class="form-control" data-parsley-required="true">
                                <form:option value="" label=""/>
                                <form:options items="${fns:getDictList('STERILIZATION_METHOD')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                            </form:select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">灭菌批号：</label>
                        <div class="col-sm-8">
                            <form:input path="sterilizationBatchNo" id="sterilizationBatchNo" htmlEscape="false" class="form-control"  maxlength="64" data-parsley-required="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">灭菌日期：</label>
                        <div class="col-sm-8">
                            <input id="sterilizationDate" name="sterilizationDate" htmlEscape="false" class="form-control Wdate" data-parsley-required="true" readonly
                                   onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">入库包装数量：</label>
                        <div class="col-sm-8">
                            <form:input path="quantity" id="quantity" htmlEscape="false" class="form-control"  maxlength="8" />
                        </div>
                    </div>
</form:form>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <input id="btnSubmit" class="btn btn-primary" type="submit" value="确 定" onclick="addRow()">&nbsp;
                        <input id="btnCancel" class="btn" type="button" value="关 闭" onclick="closeRight()"></div>
                </div>
            </div>
        </section>
    </div>
</div>

<script>
    /*消耗品自动补全*/
    autoCompleteExpPrice("remarks");
    function autoCompleteExpPrice(inputId){
        var list = $("table tr").find("td:eq(0)");  //左侧table表格数据
        var dataList = [];
        if (list.length > 0) {
            for (var i = 0; i < list.length; i++) {
                var data = jQuery.parseJSON(list[i].innerText);
                dataList.push(data);
            }
        }
        var url="${ctx}/csm/expInfo/autoCompletePrice";
        autoComplete(inputId,url,
                function(data){
                    var rows = [];
                    for(var i=0; i<data.length; i++){
                        rows[rows.length] = {
                            data:data[i],
                            value:data[i].id,
                            result:data[i].expDict.expName
                        };
                    }
                    return rows;
                },function(data, i, max){
                    return data.expDict.expName+"|"+"|"+data.packageSpec+"|"+data.expSupplierCata.supplierName;
                },function(event,data,formatted){
                    if (dataList != null && dataList != [] && typeof(dataList) != 'undefined' && dataList.length > 0) {
                        for (var i = 0; i < dataList.length; i++) {
                            console.log(dataList[i].infoId);
                            if (dataList[i].infoId == data.id) {
                                toastr.error('入库列表中该物品已经存在,请重新选择其他物品!');
                                addExpList();
                                return;
                            }
                        }
                    }
                    $('#supplierId').val(data.expSupplierCata.id);
                    $('#supplierName').attr('value',data.expSupplierCata.supplierName);
                    $('#infoId').attr('value',data.id);
                    $('#expCode').attr('value',data.expDict.expCode);
                    $('#packageSpec').attr('value',data.packageSpec);
                    $('#minSpec').attr('value',data.minSpec);
                    $('#packageNum').attr('value',data.packageNum);
                    $('#packageUnitsValue').attr('value',data.packageUnit);
                    $("#packageUnits option[value='"+data.packageUnit+"']").attr("selected", true);
                    $('#packageUnits').change();
                    $('#minUnitsValue').attr('value',data.minUnits);
                    $("#minUnits option[value='"+data.minUnits+"']").attr("selected", true);
                    $('#minUnits').change();
                })
    }
    function closeRight(){
        $("#stcokRightDiv").attr("style","display: none");
        $("#stcokLeftDiv").attr("class","main-content col-lg-12");
        $("#stcokLeftDiv").show('normal');
    }

</script>